import { constantRouterMap, asyncRouterMap } from '@/router'

function filterAsyncRouter(asyncRouterMap, pages, baseUrl) {
  const accessedRouters = asyncRouterMap.filter(route => {
    if (route.children && route.children.length) {
      route.children = filterAsyncRouter(
        route.children,
        pages,
        route.path + '/'
      )
      return route.children.length
    } else {
      return (
        pages[baseUrl + route.path] !== undefined ||
        route.path === '*' ||
        route.path === ''
      )
    }
  })
  return accessedRouters
}

const permission = {
  state: {
    routers: constantRouterMap,
    addRouters: [],
    modules: [],
    pages: []
  },
  mutations: {
    SET_MODULES: (state, modules) => {
      // state.modules = [{
      //   rowId: 0,
      //   parentId: -1,
      //   moduleUrl: '/workbench',
      //   moduleName: '首页',
      //   moduleIcon: 'home',
      //   moduleCode: '000',
      //   children: []
      // }].concat(modules)

      state.modules = modules
    },
    SET_PAGES: (state, pages) => {
      const pagesMap = {}
      pages.forEach(page => {
        pagesMap[page.opnUrl] = page
      })
      pagesMap['/workbench'] = {
        mdlCode: '000',
        mdlId: 0,
        opnCode: '',
        opnUrl: '/workbench'
      }
      state.pages = pagesMap
      state.addRouters = filterAsyncRouter(asyncRouterMap, pagesMap, '/')
    }
  },
  actions: {
    generateRoutes({ commit }, pages) {
      return new Promise(resolve => {
        resolve()
      })
    },
    setPermission({ commit }, { modules, pages }) {
      commit('SET_MODULES', modules)
      commit('SET_PAGES', pages)
      return new Promise(resolve => {
        resolve()
      })
    }
  }
}

export default permission
